/**
 * 
 */
package info.niwota.web.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Scanner;

import x.org.apache.http.NameValuePair;
import x.org.apache.http.message.BasicNameValuePair;

/**
 * @author qiangli
 *
 */
public class Utils {
	public static void parseUri(List<NameValuePair> result, String query,
			final String encoding) {
		if (query != null && query.length() > 0) {
			int idx = query.indexOf("?");
			if (idx > 0) {
				query = query.substring(idx + 1);
				parse(result, new Scanner(query), encoding);
			}
		}
	}

	public static void parseContent(List<NameValuePair> result, final String content,
			final String encoding) throws IOException {
		if (content != null && content.length() > 0) {
			parse(result, new Scanner(content), encoding);
		}
	}

	public static void parseContent(List<NameValuePair> result, final byte[] content,
			String encoding) throws IOException {
		if (content != null && content.length > 0) {
			parse(result, new Scanner(new String(content, encoding)), encoding);
		}
	}

	public static void parse(final List<NameValuePair> result, final Scanner scanner,
			final String encoding) {
		scanner.useDelimiter("&");
		while (scanner.hasNext()) {
			final String[] nvp = scanner.next().split("=");
			if (nvp.length == 0 || nvp.length > 2) {
				// throw new IllegalArgumentException("bad parameter: " +
				// Arrays.asList(nvp));
				continue; // ignore
			}
			final String name = decode(nvp[0], encoding);
			String value = null;
			if (nvp.length == 2) {
				value = decode(nvp[1], encoding);
			}
			result.add(new BasicNameValuePair(name, value));
		}
	}

	public static String decode(final String content, final String encoding) {
		try {
			return URLDecoder.decode(content, encoding != null ? encoding
					: "ISO-8859-1");
		} catch (UnsupportedEncodingException problem) {
			throw new IllegalArgumentException(problem);
		}
	}

}
